<?php
$id = $_POST['id'];
$state = $_POST['state'];
$tx_price = $_POST['tx_price'];
$proxy_acc = $_POST['proxy_acc'];
$dk_price = $_POST['dk_price'];
$notes = $_POST['notes'];
$cl_time = $_POST['cl_time'];

include_once("../../untils/conn.php");
if ($con) {
  mysqli_query($con, "set names utf8");

  // 更新 withdrawal 表
  $stmt = $con->prepare("UPDATE withdrawal SET state=?, dk_price=?, notes=?, cl_time=? WHERE id=?");
  $stmt->bind_param("ssssi", $state, $dk_price, $notes, $cl_time, $id);
  $stmt->execute();

  if ($stmt->affected_rows > 0) {
    if ($state == 2) {
      // 查询代理账户余额
      $query = $con->prepare("SELECT proxy_balance FROM proxy WHERE proxy_acc=?");
      $query->bind_param("s", $proxy_acc);
      $query->execute();
      $result = $query->get_result();

      if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $proxy_balance = $row['proxy_balance'];

        // 更新代理账户余额
        $new_proxy_balance = $proxy_balance + $tx_price;
        $update = $con->prepare("UPDATE proxy SET proxy_balance=? WHERE proxy_acc=?");
        $update->bind_param("ds", $new_proxy_balance, $proxy_acc);
        $update->execute();

        if ($update->affected_rows > 0) {
          echo "<script>alert('操作成功');window.location.href='../withdrawal.php'</script> ";
        } else {
          echo ("<script>alert('更新代理账户余额失败');window.location.replace(document.referrer)</script>");
        }
      } else {
        echo ("<script>alert('代理账户不存在');window.location.replace(document.referrer)</script>");
      }
    } else {
      echo "<script>alert('操作成功');window.location.href='../withdrawal.php'</script> ";
    }
  } else {
    echo ("<script>alert('操作失败');window.location.replace(document.referrer)</script>");
  }
}
$con->close();
?>
